<template>
  <div class="app" :class="{'bg-gradient-to-r from-gray-100 via-gray-50 to-gray-100': !isSpecialPage}">
    <!-- 标准布局 - 仅在非特殊页面显示 -->
    <template v-if="!isSpecialPage">
      <TopBar />
      <header class="header bg-white">
        <div class="container flex items-center justify-between py-6">
          <div class="logo">
            <router-link to="/" class="flex items-center">
              <img src="/logo.jpg" alt="阿蔓达医药商城" class="w-12 h-12 mr-3 rounded-lg object-cover">
              <h1 class="text-3xl font-bold text-green-600">阿蔓达医药商城</h1>
            </router-link>
          </div>
          <div class="search-bar flex-1 mx-16">
            <el-input
              v-model="searchQuery"
              placeholder="商品名称|生产厂家|商品助记码|通用名"
              size="large"
              class="input-with-select"
              @keyup.enter="handleSearch"
              clearable
              @clear="handleClear"
            >
              <template #append>
                <el-button type="danger" @click="handleSearch">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </div>
          <div class="user-actions flex items-center space-x-6">
            <el-popover placement="bottom" :width="500" trigger="hover">
              <template #reference>
                <el-button type="danger" plain @click="goToCart" class="relative">
                  <el-icon class="mr-1"><ShoppingCart /></el-icon>
                  我的购物车
                  <el-badge :value="cartCount" class="absolute -top-2 -right-2" />
                </el-button>
              </template>
              <template #default>
                <div class="cart-preview p-2 text-xs max-h-[500px] overflow-y-auto">
                  <template v-if="cartStore.cartItems.length > 0">
                    <div v-for="item in cartPreviewItems" :key="item.id" class="flex items-start gap-1.5 border-b pb-1.5 mb-1.5">
                      <img :src="item.goodsInfo.mainPic || 'https://picsum.photos/200/200'" :alt="item.goodsInfo.title" class="w-8 h-8 object-cover border rounded" />
                      <div class="flex-1 min-w-0">
                        <div class="flex items-center justify-between">
                          <p class="font-medium text-gray-800 truncate" :title="item.goodsInfo.title">{{ item.goodsInfo.title }}</p>
                          <div class="flex flex-col items-end">
                            <span class="text-red-500">{{ formatPriceAuth(item.goodsInfo.price || 0, !!userStore.token, userStore.userInfo?.discount, item.goodsInfo.noDiscounts) }}</span>
                            <span v-if="userStore.userInfo?.discount && item.goodsInfo.noDiscounts !== 1" class="text-gray-400 text-xs line-through">
                              {{ formatPriceAuth(item.goodsInfo.price || 0, !!userStore.token) }}
                            </span>
                          </div>
                        </div>
                        <div class="grid grid-cols-3 gap-x-1 gap-y-0.5 text-gray-500">
                          <div class="flex items-center">
                            <el-icon class="mr-0.5 text-gray-400 text-xs"><Document /></el-icon>
                            <span class="truncate" :title="item.goodsInfo.goodsSpec">{{ item.goodsInfo.goodsSpec }}</span>
                          </div>
                          <div class="flex items-center">
                            <el-icon class="mr-0.5 text-gray-400 text-xs"><Box /></el-icon>
                            <span class="truncate" :title="item.goodsInfo.unit">{{ item.goodsInfo.unit }}</span>
                          </div>
                          <div class="flex items-center">
                            <el-icon class="mr-0.5 text-gray-400 text-xs"><OfficeBuilding /></el-icon>
                            <span class="truncate" :title="item.goodsInfo.manufacturer">{{ item.goodsInfo.manufacturer }}</span>
                          </div>
                          <div class="flex items-center">
                            <el-icon class="mr-0.5 text-gray-400 text-xs"><Goods /></el-icon>
                            <span>库存: <span :class="getStockStatusClass(item.goodsInfo.storNum)">{{ getStockStatusText(item.goodsInfo.storNum) }}</span></span>
                          </div>
                          <div class="flex items-center">
                            <el-icon class="mr-0.5 text-gray-400 text-xs"><FirstAidKit /></el-icon>
                            <span>剂型: {{ item.goodsInfo.formula }}</span>
                          </div>
                          <div class="flex items-center">
                            <el-icon class="mr-0.5 text-gray-400 text-xs"><Stamp /></el-icon>
                            <span class="truncate" :title="item.goodsInfo.approvalNo">文号: {{ item.goodsInfo.approvalNo }}</span>
                          </div>
                        </div>
                        <div class="flex items-center justify-between mt-0.5">
                          <span class="text-gray-500 truncate" :title="item.goodsInfo.oracleGoodsName">{{ item.goodsInfo.oracleGoodsName }}</span>
                          <span class="text-gray-500">x{{ item.count }}</span>
                        </div>
                      </div>
                    </div>
                    <div class="text-right mt-2 sticky bottom-0 bg-white pt-2">
                      <p class="mb-1">共 {{ cartCount }} 件商品</p>
                      <p class="mb-1" v-if="userStore.userInfo?.discount">
                        <span class="text-gray-400 text-xs line-through">原价: {{ formatPriceAuth(cartTotal, !!userStore.token) }}</span>
                        <span class="ml-2">合计: {{ formatPriceAuth(cartTotal, !!userStore.token, userStore.userInfo?.discount) }}</span>
                      </p>
                      <p class="mb-1" v-else>
                        合计: {{ formatPriceAuth(cartTotal, !!userStore.token) }}
                      </p>
                      <el-button type="danger" size="small" @click="goToCart">去购物车结算</el-button>
                    </div>
                  </template>
                  <div v-else class="text-center text-gray-500 py-4">
                    购物车是空的
                  </div>
                </div>
              </template>
            </el-popover>
            <el-dropdown>
              <span class="el-dropdown-link flex items-center cursor-pointer text-gray-600 hover:text-red-500">
                <img 
                  v-if="userStore.userInfo?.avatarUrl" 
                  :src="userStore.userInfo.avatarUrl" 
                  :alt="userStore.userInfo?.nickName"
                  class="w-8 h-8 rounded-full object-cover mr-2"
                  @error="handleAvatarError"
                />
                <el-icon v-else class="mr-1"><User /></el-icon>
                {{ userStore.userInfo?.nickName || '个人中心' }}
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="$router.push('/profile/footprints')">
                    <el-icon><User /></el-icon>
                    个人信息
                  </el-dropdown-item>
                  <el-dropdown-item @click="$router.push('/profile/favorites')">
                    <el-icon><Star /></el-icon>
                    收藏商品
                  </el-dropdown-item>
                  <el-dropdown-item @click="$router.push('/profile/footprints')">
                    <el-icon><FootprintIcon /></el-icon>
                    我的足迹
                  </el-dropdown-item>
                  <el-dropdown-item @click="$router.push('/profile/password')">
                    <el-icon><Lock /></el-icon>
                    安全设置
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="handleLogout">
                    <el-icon><SwitchButton /></el-icon>
                    退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
      
          </div>
        </div>
      </header>
      <HeaderNav />

      <main class="main py-2 pb-6">
        <div class="container">
          <router-view :key="$route.fullPath" />
        </div>
      </main>

      <AppFooter />
      <FixedButtons />
    </template>

    <!-- 特殊页面布局 - 直接显示路由内容，不包含通用布局 -->
    <template v-else>
      <router-view />
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import TopBar from './components/layout/TopBar.vue'
import HeaderNav from './components/layout/HeaderNav.vue'
import AppFooter from './components/layout/AppFooter.vue'
import FixedButtons from './components/layout/FixedButtons.vue'
import FootprintIcon from '@/components/icons/FootprintIcon.vue'
import { Search, ShoppingCart, User, ArrowDown, Document, Box, OfficeBuilding, Goods, FirstAidKit, Stamp, Star, Lock, SwitchButton } from '@element-plus/icons-vue'
import { useCartStore } from '@/stores/cart'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'


import { getStockStatusText, getStockStatusClass } from '@/lib/stockUtils'
import { formatPriceAuth } from '@/lib/utils'

const searchQuery = ref('')
const router = useRouter()
const route = useRoute()
const cartStore = useCartStore()
const userStore = useUserStore()

// 监听路由变化，同步搜索关键词
watch(() => route.query.keyWord, (newKeyWord) => {
  if (route.path === '/products' || route.path === '/next-products') {
    searchQuery.value = newKeyWord ? String(newKeyWord) : ''
  }
}, { immediate: true })

// 定义特殊页面路径列表 - 这些页面不使用通用布局
const specialPages = ['/login', '/register', '/forgot-password']

// 计算当前页面是否为特殊页面
const isSpecialPage = computed(() => {
  return specialPages.includes(route.path)
})

// 处理搜索
function handleSearch() {
  const trimmedQuery = searchQuery.value.trim()
  
  if (route.path === '/products' || route.path === '/next-products') {
    // 如果已经在商品列表页面，直接更新查询参数，保持当前路径
    const query = { ...route.query }
    if (trimmedQuery) {
      query.keyWord = trimmedQuery
    } else {
      // 如果搜索内容为空，删除 keyWord 参数
      delete query.keyWord
    }
    router.replace({
      path: route.path,
      query
    })
  } else {
    // 如果不在商品列表页面
    if (trimmedQuery) {
      // 有搜索内容时跳转到普通商品页面
      router.push({
        path: '/products',
        query: { keyWord: trimmedQuery }
      })
    } else {
      // 搜索内容为空时跳转到普通商品页面且不带关键词
      router.push({ path: '/products' })
    }
  }
}

// 处理搜索框清空
function handleClear() {
  if (route.path === '/products' || route.path === '/next-products') {
    // 如果已经在商品列表页面，直接更新查询参数，保持当前路径
    const query = { ...route.query }
    delete query.keyWord
    router.replace({
      path: route.path,
      query
    })
  }
}

function goToCart() {
  router.push('/cart')
}

// 获取用户信息
async function fetchUserInfo() {
  try {
    if (userStore.token) {
      await userStore.fetchUserInfo()
    }
  } catch (error) {
    console.error('Failed to fetch user info:', error)
  }
}

// 在组件挂载时获取购物车数据和用户信息
onMounted(async () => {
  await cartStore.fetchCartList()
  await fetchUserInfo()
})

// 监听购物车数据变化
watch(() => cartStore.cartItems, (newItems) => {
  console.log('购物车数据已更新:', newItems)
}, { deep: true })

// 监听 token 变化
watch(() => userStore.token, (newToken) => {
  if (newToken) {
    cartStore.fetchCartList()
  }
})

// 购物车预览内容
const cartPreviewItems = computed(() => {
  return cartStore.cartItems.slice(0, 8) // 显示前8个商品
})

// 购物车总价
const cartTotal = computed(() => {
  return cartStore.cartTotal.toFixed(2)
})

// 购物车商品总数
const cartCount = computed(() => {
  return cartStore.cartCount
})

async function handleLogout() {
  try {
    // TODO: Call your logout API
    await userStore.logout()
    ElMessage.success('退出登录成功')
    router.push('/login')
  } catch (error) {
    console.error('Logout failed:', error)
    ElMessage.error('退出登录失败，请重试')
  }
}

function handleAvatarError() {
  // Handle avatar loading error
  console.error('Failed to load avatar')
}
</script>

<style>
.app {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  border-bottom: 1px solid #e5e5e5;
}

.main {
  flex: 1;
}

.search-bar .el-input-group__append {
  background-color: #e1251b;
  border-color: #e1251b;
  color: white;
}
.search-bar .el-input-group__append .el-button {
   color: white;
   background-color: transparent;
   border: none;
}
.search-bar .el-input-group__append .el-button:hover {
  background-color: #c81623;
  border-color: #c81623;
}
.el-dropdown-link {
  outline: none;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 15px;
}
</style> 